package com.guaoran.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author : 顾成
 * @title : FilesUtils 
 * @Description : 
 * 	file文件工具包
 * @date :2016-6-18下午7:09:51
 */
public class FilesUtils {
	private static Logger log = LoggerFactory.getLogger(FilesUtils.class);
	private static final int FILE_BUFFER_SIZE = 2048;

    /**
     * 文件上传 :适合MultipartFile file
     * @param file ：文件流
     * @param fileName ：文件名称
     * @param filePath ：上传的路径
     */
    public static void uploadFile (MultipartFile file, String fileName, String filePath){
    	RandomAccessFile oSavedFile = null;
    	BufferedInputStream inputStream = null;
    	try {
			File tempFile = new File(filePath + File.separator + fileName);
        	log.info("uploadFile==>uploadPath="+filePath +"/"+ fileName);
        	File rootFile=tempFile.getParentFile();//得到父文件夹
        	//不存在 则创建一个文件
        	if(!tempFile.exists()){
        		rootFile.mkdirs();
        		tempFile.createNewFile();
        	}
			oSavedFile = new RandomAccessFile(tempFile, "rw");
			// 定位文件指针到 nPos 位置
			oSavedFile.seek(0);
			//获取video的媒资数据判断是否上传完成
			byte[] buffer = new byte[2048];
			int readBytes = 0;
			inputStream = new BufferedInputStream(file.getInputStream());
			// 从输入流中读入字节流，然后写到文件中
			while ((readBytes = inputStream.read(buffer)) > 0) {
				oSavedFile.write(buffer, 0, readBytes);
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("uploadFile==>Exception:"+e.getMessage());
		}finally{
			try {
                if(inputStream != null) {
                	inputStream.close();
                    inputStream = null;
                }
            } catch (IOException e) {
            	e.printStackTrace();
            }
            try {
                if (oSavedFile != null) {
                	oSavedFile.close();
                	oSavedFile = null;
                }
            } catch (IOException e) {
            	e.printStackTrace();
            }
		}
    }
	/**
	 * 文件上传 :适合 InputStream
	 * @param in ：文件流
	 * @param fileName ：文件名称
	 * @param filePath ：上传的路径
	 */
	public static void uploadFileInputStream (InputStream in, String fileName, String filePath){
		RandomAccessFile oSavedFile = null;
		BufferedInputStream inputStream = null;
		try {
			File tempFile = new File(filePath + File.separator + fileName);
			log.info("uploadFile==>uploadPath="+filePath +"/"+ fileName);
			File rootFile=tempFile.getParentFile();//得到父文件夹
			//不存在 则创建一个文件
			if(!tempFile.exists()){
				rootFile.mkdirs();
				tempFile.createNewFile();
			}
			oSavedFile = new RandomAccessFile(tempFile, "rw");
			// 定位文件指针到 nPos 位置
			oSavedFile.seek(0);
			//获取video的媒资数据判断是否上传完成
			byte[] buffer = new byte[2048];
			int readBytes = 0;
			inputStream = new BufferedInputStream(in);
			// 从输入流中读入字节流，然后写到文件中
			while ((readBytes = inputStream.read(buffer)) > 0) {
				oSavedFile.write(buffer, 0, readBytes);
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("uploadFile==>Exception:"+e.getMessage());
		}finally{
			try {
				if(inputStream != null) {
					inputStream.close();
					inputStream = null;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if (oSavedFile != null) {
					oSavedFile.close();
					oSavedFile = null;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
     * 文件下载
     * @param absolutelyPath ：文件的绝对路径
     * @param response
     * @param request
     * @throws Exception
     */
	public static void downloadFileAbsolutely(String absolutelyPath, HttpServletResponse response,
                                              HttpServletRequest request) throws Exception {
		log.info("downloadFile==>downFilePath=" + absolutelyPath);
		File file = new File(absolutelyPath);
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		OutputStream fos = null;
		InputStream fis = null;
		if (!file.exists()) {
			log.info("downloadFile==>fail==>file not exist");
			return;
		}
		try {
			fis = new FileInputStream(file);
			bis = new BufferedInputStream(fis);
			fos = response.getOutputStream();
			bos = new BufferedOutputStream(fos);
			setFileDownloadHeader(request, response,file.getName());
			int byteRead = 0;
			byte[] buffer = new byte[FILE_BUFFER_SIZE];
			while ((byteRead = bis.read(buffer)) >0) {
				bos.write(buffer, 0, byteRead);
			}
		} catch (Exception e) {
			log.info("downloadFile..fail..="+e.getMessage());
		}finally {
			bos.flush();
			if (fis != null) {
                try {
                	fis.close();
                	fis = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
			if (bis != null) {
				try {
					bis.close();
					bis = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (fos != null) {
				try {
					fos.close();
					fos = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (bos != null) {
				try {
					bos.close();
					bos = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * 设置让浏览器弹出下载对话框的Header.
	 * 根据浏览器的不同设置不同的编码格式  防止中文乱码
	 * @param fileName 下载后的文件名.
	 */
	public static void setFileDownloadHeader(HttpServletRequest request, HttpServletResponse response,
                                             String fileName) {
	    try {
	        //中文文件名支持
	        String encodedfileName = null;
	        String agent = request.getHeader("USER-AGENT");
	        if(null != agent && -1 != agent.indexOf("MSIE")){//IE
	            encodedfileName = java.net.URLEncoder.encode(fileName,"UTF-8");
	        }else if(null != agent && -1 != agent.indexOf("Mozilla")){
	            encodedfileName = new String(fileName.getBytes("UTF-8"),"iso-8859-1");
	        }else{
	            encodedfileName = java.net.URLEncoder.encode(fileName,"UTF-8");
	        }
	        response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedfileName + "\"");
	    } catch (UnsupportedEncodingException e) {
	        e.printStackTrace();
	    }
	}
	
	/**
     * 递归删除目录下的所有文件及子目录下所有文件
     * @param dir 将要删除的文件目录
     */
    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            //递归删除目录中的子目录下
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空，可以删除
        return dir.delete();
    }

}
